import json
import requests

from config.env_config import env_config
from utils.logger import logger


class BaseHttpAction(object):
    """基础http请求类，其他的http请求全部基于该类"""

    def basePost(self, url, params, headers={"content-type": "application/json;charset=utf-8"}):
        """post 请求"""
        logger.info("POST: %s" % url)
        jsonData = json.dumps(params, ensure_ascii=False)
        logger.info("请求参数：%s" % jsonData)
        resp = requests.post(url, data=jsonData.encode("utf-8"), headers=headers, verify=False)
        return self.__checkAndParse(resp)

    def basePostParams(self, url, data, params, headers={"content-type": "application/json;charset=utf-8"}):
        """post 请求"""
        logger.info("POST: %s" % url)
        jsonData = json.dumps(data, ensure_ascii=False)
        logger.info("请求参数：%s" % jsonData)
        resp = requests.post(url, data=jsonData.encode("utf-8"), params=params, headers=headers, verify=False)
        return self.__checkAndParse(resp)

    def baseGet(self, url, params, headers={}):
        """get 请求"""
        jsonData = json.dumps(params, ensure_ascii=False)
        logger.info("请求参数：%s" % jsonData)
        resp = requests.get(url, params=params, headers=headers, verify=False)
        logger.info("GET: %s" % resp.url)
        return self.__checkAndParse(resp)

    def basePut(self, url, params, headers={"content-type": "application/json;charset=utf-8"}):
        """get 请求"""
        jsonData = json.dumps(params, ensure_ascii=False)
        logger.info("请求头：%s" % headers)
        logger.info("请求参数：%s" % jsonData)
        resp = requests.put(url, data=jsonData, headers=headers, verify=False)
        logger.info("PUT: %s" % resp.url)
        return self.__checkAndParse(resp)

    @staticmethod
    def __checkAndParse(resp):
        if resp.status_code != 200:
            try:
                text = resp.json()
                logger.error("http status is %s" % resp.status_code)
                logger.error("错误响应：%s" % json.dumps(text, ensure_ascii=False))
            except:
                text = resp.text
                logger.error("response: %s" % json.dumps(text, ensure_ascii=False))
            return text
        try:
            logger.info("response: %s" % json.dumps(resp.json(), ensure_ascii=False))
            return resp.json()
        except:
            logger.info("response: %s" % json.dumps(resp.text, ensure_ascii=False))
            return resp.text


class PMSHttpAction(BaseHttpAction):

    def __init__(self):
        self.__basePath = "%s/pms-svc/v1" % env_config.base_url

    def get(self, url, data={}, token=''):
        print(self.__basePath)
        pmsPath = self.__basePath + url
        headers = {"Authorization": "Bearer %s" % token}
        return super().baseGet(pmsPath, data, headers)

    def post(self, url, data={}, token=''):
        pmsPath = '%s%s' % (self.__basePath, url)
        headers = {"content-type": "application/json;charset=utf-8",
                   "Authorization": "Bearer %s" % token
                   }
        return super().basePost(pmsPath, data, headers)

    def put(self, url, data={}, token=''):
        print(self.__basePath)
        pmsPath = self.__basePath + url
        headers = {
            "content-type": "application/json;charset=utf-8",
            "Authorization": "Bearer %s" % token
        }
        return super().basePut(pmsPath, data, headers)


pms_http = PMSHttpAction()


class TDPHttpAction(BaseHttpAction):

    def __init__(self):
        self.__basePath = "%s/tdp/v1" % env_config.tdp_url


    def get(self, url, data={}):
        print(self.__basePath)
        tdpPath = self.__basePath + url
        return super().baseGet(tdpPath, data)

    def post(self, url, data={}):
        tdpPath = '%s%s' % (self.__basePath, url)
        return super().basePost(tdpPath, data )

    def postCmd(self, cmd, data={}, env=env_config.DEFAULT_ENV):
        '''以命令的形式访问tdp造数据方法'''
        tdpPath = self.__basePath + '/interface/commandExec/form_data'
        param = ""
        for item in data:
            param = "%s%s:%s\n" % (param, item, data[item])
            print(item)
        requestData = {
            "name": cmd,
            "requestMethod": "指令",
            "env": env,
            "param": param
        }
        print(requestData)
        return super().basePost(tdpPath, requestData)


tdp_http = TDPHttpAction()


class TpHttpAction(BaseHttpAction):

    def __init__(self, service):
        self.__basePath = "%s/%s/v1" % (env_config.base_url, service)

    def get(self, url, data={}):
        print(self.__basePath)
        tpPath = self.__basePath + url
        return super().baseGet(tpPath, data)


    def post(self, url, data={}):
        tpPath = '%s%s' % (self.__basePath, url)
        return super().basePost(tpPath, data)


trade_http = TpHttpAction(service='trade')
pomodel_http = TpHttpAction(service='pomodel')